import requests
import json
from langchain.prompts import PromptTemplate

API_URL = 'http://10.1.161.53:11434/api/chat'
MODEL_NAME = "deepseek-r1:70b"


def analyze_boat_flow_api_data(question, sql_result):
    """基于SQL查询结果生成数据分析报告（流式输出）

    Args:
        question: 需要分析的业务问题
        sql_result: SQL查询结果字符串

    Returns:
        生成器，逐块返回分析报告内容
    """
    analysis_prompt = PromptTemplate.from_template(
        """根据问题：{test_question}  
SQL查询结果：{sql_result}  
根据SQL查询结果分为两种情况，根据实际返回的结果，选择其中的一个回复问题
- 如果有查询结果，请提供：  
    1. 数据的简明分析
    2. 关键业务见解

- 如果查询结果为空，请提供：  
    1. 数据的简明分析
    2. 分析可能的原因（数据缺失、查询日期条件限制等）  
    3. 提出2-3个相关的跟进问题，帮助进一步明确用户需求
 

使用简洁专业的语言，避免冗余解释和Markdown格式。 
        """
    )

    formatted_prompt = analysis_prompt.format(
        test_question=question,
        sql_result=sql_result
    )

    data = {
        "model": MODEL_NAME,
        "messages": [
            {"role": "system", "content": "你是一个专业的数据分析助理，擅长解读SQL查询结果并提出业务建议"},
            {"role": "user", "content": formatted_prompt}
        ],
        "stream": True
    }

    response = requests.post(
        API_URL,
        data=json.dumps(data),
        stream=True,
        headers={'Content-Type': 'application/json'}
    )
    response.raise_for_status()

    # 返回生成器，逐块返回内容
    for chunk in response.iter_lines():
        if chunk:
            decoded = json.loads(chunk.decode('utf-8'))
            if 'message' in decoded and 'content' in decoded['message']:
                content = decoded['message']['content']
                yield content  # 直接返回每个内容块


# 使用示例（外部处理流式响应）
# if __name__ == "__main__":
#     question = "江海货368 2025年2月20日航行轨迹"
#     sql_result = """{\"total\":4,\"pageIndex\":1,\"pageSize\":500,\"rows\":[{\"bayonetName\":\"杭申线卡口\",\"boatName\":\"江海货368\",\"code\":\"hs899912\",\"direction\":\"入沪\",\"endPoint\":\"-43720.947,-30818.384\",\"imagePaths\":\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P0_20250220_104230.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P1_20250220_104230.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P2_20250220_104230.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P3_20250220_104230.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P4_20250220_104230.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P5_20250220_104230.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P6_20250220_104230.jpg;\",\"imageUrls\":[\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P0_20250220_104230.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P1_20250220_104230.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P2_20250220_104230.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P3_20250220_104230.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P4_20250220_104230.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P5_20250220_104230.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/10/P6_20250220_104230.jpg\"],\"load\":\"空载\",\"locationMapx\":-43720.947,\"locationMapy\":-30818.384,\"passTime\":\"2025-02-20 10:42:30.0\",\"speed\":3.69},{\"bayonetName\":\"黄浦江(松浦大桥南岸)\",\"boatName\":\"江海货368\",\"code\":\"5B16DC01A68A4D42A002C7A2F2A52192\",\"direction\":\"出沪\",\"endPoint\":\"-14860.154,-29250.958\",\"imagePaths\":\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P0_20250220_131544.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P1_20250220_131544.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P2_20250220_131544.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P3_20250220_131544.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P4_20250220_131544.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P5_20250220_131544.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P6_20250220_131544.jpg;\",\"imageUrls\":[\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P0_20250220_131544.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P1_20250220_131544.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P2_20250220_131544.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P3_20250220_131544.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P4_20250220_131544.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P5_20250220_131544.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/13/P6_20250220_131544.jpg\"],\"load\":\"空载\",\"locationMapx\":-14860.154,\"locationMapy\":-29250.958,\"passTime\":\"2025-02-20 13:15:44.0\",\"speed\":7.05},{\"bayonetName\":\"黄浦江(松浦大桥南岸)\",\"boatName\":\"江海货368\",\"code\":\"6F3D7264A98D4A98BAE69ED4360AC62F\",\"direction\":\"入沪\",\"endPoint\":\"-14860.154,-29250.958\",\"imagePaths\":\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P0_20250220_180620.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P1_20250220_180620.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P2_20250220_180620.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P3_20250220_180620.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P4_20250220_180620.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P5_20250220_180620.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P6_20250220_180620.jpg;/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P7_20250220_180620.jpg;\",\"imageUrls\":[\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P0_20250220_180620.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P1_20250220_180620.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P2_20250220_180620.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P3_20250220_180620.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P4_20250220_180620.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P5_20250220_180620.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P6_20250220_180620.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/8/2025/20250220/18/P7_20250220_180620.jpg\"],\"load\":\"重载\",\"locationMapx\":-14860.154,\"locationMapy\":-29250.958,\"passTime\":\"2025-02-20 18:06:20.0\",\"speed\":4.76},{\"bayonetName\":\"杭申线卡口\",\"boatName\":\"江海货368\",\"code\":\"hs900142\",\"direction\":\"出沪\",\"endPoint\":\"-43720.947,-30818.384\",\"imagePaths\":\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P0_20250220_214525.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P1_20250220_214525.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P2_20250220_214525.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P3_20250220_214525.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P4_20250220_214525.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P5_20250220_214525.jpg;/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P6_20250220_214525.jpg;\",\"imageUrls\":[\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P0_20250220_214525.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P1_20250220_214525.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P2_20250220_214525.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P3_20250220_214525.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P4_20250220_214525.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P5_20250220_214525.jpg\",\"/data/dataShareFolder/bayonetPhoto/origin/1/2025/20250220/21/P6_20250220_214525.jpg\"],\"load\":\"重载\",\"locationMapx\":-43720.947,\"locationMapy\":-30818.384,\"passTime\":\"2025-02-20 21:45:25.0\",\"speed\":3.69}]}"""
#     # sql_result = ""
#     print("\n开始生成分析报告：")
#     try:
#         # 遍历生成器逐块处理
#         for content in analyze_boat_flow_api_data(question, sql_result):
#             print(content, end="", flush=True)  # 外部处理实时输出
#     except Exception as e:
#         print(f"请求失败: {str(e)}")
#     finally:
#         print("\n数据分析完成")